import json
import random
import re

from flask import Blueprint, jsonify, request, make_response
from application.models.users.user import db, User
from ronglian_sms_sdk import SmsSDK
from application.captcha.captcha import captcha
from RedisTool import r
from werkzeug.security import generate_password_hash, check_password_hash
from tools.comm import sendMsg
user_blue = Blueprint("user_blue", __name__)


# 获取图片验证码
@user_blue.route("/getcode")
def getcode():
    # 生成图片验证码 text文字， image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid作为redis key
    uuid = str(request.args.get("uuid"))
    # 存入redis
    r.str_add(uuid, str(text), 60)
    # 以流方式返回图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = "image/png"
    return res


# 发送短信验证码
@user_blue.route("/sendSmsCode", methods=["POST"])
def sendSmsCode():
    data = request.data
    if data:
        data = json.loads(data)
        # 获取三个参数
        uuid = data.get("uuid")
        mobile = data.get("mobile")
        procode = data.get("procode")
        # 通过uuid查询redis
        value = r.str_get(uuid)
        # 两个验证码对比，如果成功调用短信平台发送短信 # lower() 转换为小写
        if value:
            if procode.lower() == value.lower():
                # 验证一分钟只能发送一次
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({"code": 403, "msg": "一分钟只能发送一次"})
                    # 生成5位随机数
                # scode = "%06d" % random.randint(0, 999999)
                scode = random.randint(10000, 99999)
                scode = str(scode)
                flag = sendMsg(mobile, scode)
                if flag == True:
                    r.str_add(mobile, scode, 60)
                    r.str_del(uuid)
                    return jsonify({"code": 200, "msg": "发送成功"})
                else:
                    return jsonify({"code": 404, "msg": "发送失败"})
            else:
                return jsonify({"code": 402, "msg": "图形验证码错误"})
        else:
            return jsonify({"code": 401, "msg": "图形验证码不存在"})


# 注册登录接口
@user_blue.route("/login", methods=["POST"])
def login():
    # 获取参数、手机号、验证码
    data = request.data
    if data:
        data = json.loads(data)
        uuid = data.get("uuid")
        procode = data.get("smscode")
        mobile = data.get("mobile")
        # 根据手机号跟redis获取验证码
        mobile_code = r.str_get(mobile)
        # 验证码是否相同
        if str(mobile_code) == str(procode):
            print("mobile_code>>>>>>>>>", mobile_code)
            print("procode>>>>>>>>>", procode)
            # 如果相同查询数据库user表
            user = User.query.filter(User.mobile == mobile).first()
            # 删除redis中的验证码
            if user:
                r.str_del(mobile)
            else:
                # 如果不存在写入用户表
                u = User(mobile=mobile, nikename=mobile)
                db.session.add(u)
                db.session.commit()
                # 如果存在返回用户信息
                user = User.query.filter(User.mobile == mobile).first()
            # 用用户信息生成jwt.token
            token = str(random.randint(100, 1000))
            return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": user.id})
        # 如果不相同返回错误
        else:
            return jsonify({"code": 400, "msg": "验证码错误"})
    else:
        return jsonify({"code": 401, "msg": "数据不存在"})
















